<template>
  <a-drawer :title="title" v-model:open="open" :width="520">
    <a-form :label-col="formCol.labelCol" 
            :wrapper-col="formCol.wrapperCol" 
            ref="formRef" 
            :rules="rules"
            :model=form> 
      <a-form-item label="模板名称" name="name">
        <a-input  placeholder="请输入模板名称" v-model:value="form.name"  name="name"/>
      </a-form-item>
      <a-form-item label="模板字段" name="fields">
        <div class="checkbox">
          <div class="checkbox-header">
            <span>
              <a-form-item-rest>
                <a-checkbox :indeterminate="state.indeterminate" v-model:checked="state.checkAll" @change="onChange"/> 全选 / 全不选
              </a-form-item-rest>
            </span>
            <span>已选 {{ form.fields.length }} 项</span>
          </div>
          <a-checkbox-group name="fields" v-model:value="form.fields" :style="{display:'block'}">
            <div class="checkbox-group">
              <div class="checkbox-item" v-for="item in fields" key="item.id">
                <a-checkbox :value="item.id" :style="{display:'flex',flex:1}">
                  {{item.name}} <span class="a-text-secondary">{{ item.field_type }}</span>
                </a-checkbox>
              </div>
            </div>
          </a-checkbox-group>
        </div>
      </a-form-item>
      <a-form-item label="描述" name="description">
        <a-textarea placeholder="请输入模板描述" v-model:value="form.description" show-count :maxlength="50" />
      </a-form-item>
      <a-form-item label="受否启用" name="status">
        <a-radio-group name="status" v-model:value="form.status" buttonStyle="solid">
          <a-radio-button :value="1">是</a-radio-button>
          <a-radio-button :value="0">否</a-radio-button>
        </a-radio-group>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-flex justify="end" gap="middle">
        <a-button @click="open = false">取消</a-button>
        <a-button type="primary" @click="handleOk" :loading="loading">确定</a-button>
      </a-flex>
    </template>
  </a-drawer>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { formCol} from '@/config';
import { getFieldsStatus } from '@/server/modules/fields';
import useMessage from '@/hooks/useMessage';
import { createTemplate,updateTemplate } from '@/server/modules/templates';

type FieldsType = {id:number,name:string,field_type:string,status:number}

const {dataItem} = defineProps<{dataItem?: TemplateType}>()
const open = defineModel<boolean>('open')
const emits = defineEmits(['ok']);
const loading = ref(false);
const title = computed(() => dataItem?.id ? '编辑模板' : '新增模板');
const formRef = ref();
const fields = ref<FieldsType[]>([])
const state = reactive({
  indeterminate: false,
  checkAll: false,
  fieldsKeys: [] as number[],
})

const form = reactive<TemplateTypeForm>({
  id:0,
  name: '',
  fields: [],
  description: '',
  status: 1
});
const rules = {
  name:[{required:true,message:'请输入模板名称',trigger:'blur'}],
  fields:[{required:true,message:'请选择模板字段',trigger:'change'}],
}
// 获取允许使用的字段列表
const getFieldsList = async() => {
  const res = await getFieldsStatus()
  if(res.code === 200){
    fields.value = res.data
    //获取所有fields id
    state.fieldsKeys = fields.value.map((item:any) => item.id)
  }
}
//监听fields change
const onChange = (e: any) => {
  form.fields = e.target.checked ? state.fieldsKeys : [];
  state.indeterminate = false;
};
//监听fields indeterminate change
watch(() => form.fields,(val)=>{
  state.checkAll = !!val.length && val.length === state.fieldsKeys.length;
  state.indeterminate = !!val.length && val.length < state.fieldsKeys.length;
})
//监听dataItem 赋值表单
watch(() => dataItem, (val) => {
  if (val) {
    Object.assign(form, val);
  }else{
    form.id =0;
    form.fields = [];
    form.description = '';
    form.name = '';
    form.status = 1;
  }
},{immediate: true})
//初始化请求fields
onMounted(() => {
  getFieldsList()
})

//提交表单
const handleOk = async() => {
  try{
    loading.value = true
    await formRef.value?.validate()
    //根据form.id判断是更新还是创建
    const res = await ( form.id ? updateTemplate(form) : createTemplate(form))
    if(res.code === 200){
      open.value = false
      emits('ok')
    }
    useMessage(res.code,res.message)
  }catch(err){
    useMessage(0,'请检查必填字段')
  }finally{ 
    setTimeout(() => {
      loading.value = false;
    }, 2000);
  }
  loading.value = true;
};

</script>

<style scoped>
.checkbox {
  border:1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}
.checkbox-header {
  padding: 8px 12px 9px;
  border-bottom: 1px solid #d9d9d9;
  display: flex;
  justify-content: space-between;
}
.checkbox-group {
  display: block;
  flex-direction:column;
  flex-wrap: wrap;
  height: 200px;
  overflow-y:auto ;
}
.checkbox-item {
  display: block;
  padding: 6px 12px;
}
.checkbox-item:hover{
  background-color: #f5f5f5;
  transition: var(--transition);
}
</style>